#!/usr/bin/env python3
"""
最小化MCP Stdio测试 - 不依赖任何配置文件
"""

import asyncio
import json
import sys
from typing import Dict, Any

class MinimalMCPServer:
    """最小化MCP服务器"""
    
    def __init__(self):
        self.tools = {
            "echo": {
                "description": "Echo back the input",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "message": {
                            "type": "string",
                            "description": "Message to echo back"
                        }
                    },
                    "required": ["message"]
                }
            }
        }
        
    async def handle_message(self, message: Dict[str, Any]) -> Dict[str, Any]:
        """处理MCP消息"""
        method = message.get("method")
        msg_id = message.get("id")
        
        if method == "initialize":
            return {
                "jsonrpc": "2.0",
                "id": msg_id,
                "result": {
                    "protocolVersion": "2024-11-05",
                    "capabilities": {
                        "tools": {},
                        "resources": {}
                    },
                    "serverInfo": {
                        "name": "minimal-mcp-server",
                        "version": "1.0.0"
                    }
                }
            }
        elif method == "tools/list":
            return {
                "jsonrpc": "2.0",
                "id": msg_id,
                "result": {
                    "tools": [
                        {
                            "name": "echo",
                            "description": self.tools["echo"]["description"],
                            "inputSchema": self.tools["echo"]["inputSchema"]
                        }
                    ]
                }
            }
        elif method == "tools/call":
            params = message.get("params", {})
            tool_name = params.get("name")
            arguments = params.get("arguments", {})
            
            if tool_name == "echo":
                message_text = arguments.get("message", "")
                return {
                    "jsonrpc": "2.0",
                    "id": msg_id,
                    "result": {
                        "content": [
                            {
                                "type": "text",
                                "text": f"Echo: {message_text}"
                            }
                        ]
                    }
                }
            else:
                return {
                    "jsonrpc": "2.0",
                    "id": msg_id,
                    "error": {
                        "code": -32601,
                        "message": f"Unknown tool: {tool_name}"
                    }
                }
        else:
            return {
                "jsonrpc": "2.0",
                "id": msg_id,
                "error": {
                    "code": -32601,
                    "message": f"Unknown method: {method}"
                }
            }

async def stdio_loop():
    """Stdio消息循环"""
    server = MinimalMCPServer()
    
    print("Minimal MCP Server started", file=sys.stderr)
    
    try:
        while True:
            # 读取一行输入
            line = await asyncio.get_event_loop().run_in_executor(
                None, sys.stdin.readline
            )
            
            if not line:
                break
                
            line = line.strip()
            if not line:
                continue
                
            try:
                # 解析JSON消息
                message = json.loads(line)
                print(f"Received: {message}", file=sys.stderr)
                
                # 处理消息
                response = await server.handle_message(message)
                
                # 发送响应
                response_json = json.dumps(response)
                print(response_json)
                sys.stdout.flush()
                print(f"Sent: {response}", file=sys.stderr)
                
            except json.JSONDecodeError as e:
                print(f"JSON decode error: {e}", file=sys.stderr)
            except Exception as e:
                print(f"Error processing message: {e}", file=sys.stderr)
                
    except Exception as e:
        print(f"Stdio loop error: {e}", file=sys.stderr)

if __name__ == "__main__":
    asyncio.run(stdio_loop())